dp implementation two pointers *1400

Please click on ads to support us..

Python Code:

n=int(input())
a=list(map(int,input().split()))
a1=[a[0]]
a2=[0]
DA=0
if len(set(a))<=2:
    print(n)
else:
    for i in range(n):
        if a[i]!=a1[-1]:
            a1.append(a[i])
            a2.append(i)
    a2.append(n)
    xn1=0
    xn2=1
    i=2
    la1=len(a1)
    while i<la1:
        if a1[i]!=a1[xn1] and a1[i]!=a1[xn2]:
            DA1=a2[i]-a2[xn1]
            if DA<DA1:
                DA=DA1
            xn1=i-1
            xn2=i
        i+=1
    else:
        DA1 = a2[i] - a2[xn1]
        if DA < DA1:
            DA = DA1
    print(DA)

C++ Code:

#include <bits/stdc++.h>
using namespace std;

const int N = 3e6 + 2;
int n, A[N], limit = 1;

int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    cin >> n;
	for (int i = 0; i < n; i++) cin >> A[i];
	deque<int> mx, mn;
	int i = 0, j;
	for (j = 0; j < n; j++) {
		while (!mx.empty() && A[j] > mx.back()) mx.pop_back();
		while (!mn.empty() && A[j] < mn.back()) mn.pop_back();
		mx.push_back(A[j]);
		mn.push_back(A[j]);
		if (mx.front() - mn.front() > limit) {
			if (mx.front() == A[i]) mx.pop_front();
			if (mn.front() == A[i]) mn.pop_front();
			i++;
		}
	}
	cout << j - i << '\n';
}


Comments

Submit
0 Comments
More Questions

792A - New Bus Route
221A - Little Elephant and Function
492C - Vanya and Exams
1369B - AccurateLee
892B - Wrath
999A - Mishka and Contest
727C - Guess the Array
1625C - Road Optimization
1715D - 2+ doors
267A - Subtractions
1582A - Luntik and Concerts
560A - Currency System in Geraldion
946A - Partition
1068B - LCM
1692E - Binary Deque
679A - Bear and Prime 100
488A - Giga Tower
14A - Letter
1150A - Stock Arbitraging
1552A - Subsequence Permutation
1131F - Asya And Kittens
1475F - Unusual Matrix
133B - Unary
1547A - Shortest Path with Obstacle
624A - Save Luke
1238A - Prime Subtraction
1107C - Brutality
1391B - Fix You
988B - Substrings Sort
312A - Whose sentence is it